<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="配置名称" prop="configName">
              <el-input v-model="queryParams.configName" placeholder="请输入配置名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="配置键" prop="configKey">
              <el-input v-model="queryParams.configKey" placeholder="请输入配置键" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="配置分组" prop="configGroup">
              <el-select v-model="queryParams.configGroup" placeholder="请选择配置分组" clearable>
                <el-option label="基础配置" value="base" />
                <el-option label="系统配置" value="system" />
                <el-option label="上传配置" value="upload" />
                <el-option label="其他配置" value="other" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['cms:config:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['cms:config:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['cms:config:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['cms:config:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="配置名称" align="center" prop="configName" />
        <el-table-column label="配置键" align="center" prop="configKey" />
        <el-table-column label="配置值" align="center" prop="configValue" show-overflow-tooltip />
        <el-table-column label="配置类型" align="center" prop="configType" width="100">
          <template #default="scope">
            <el-tag :type="getConfigTypeTag(scope.row.configType)">
              {{ getConfigTypeLabel(scope.row.configType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="配置分组" align="center" prop="configGroup" width="100">
          <template #default="scope">
            <el-tag :type="getConfigGroupTag(scope.row.configGroup)">
              {{ getConfigGroupLabel(scope.row.configGroup) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" width="80" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['cms:config:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['cms:config:remove']"
              :disabled="scope.row.isSystem === '1'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改CMS系统配置对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="configFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="配置名称" prop="configName">
          <el-input v-model="form.configName" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="配置键" prop="configKey">
          <el-input v-model="form.configKey" placeholder="请输入配置键" :disabled="form.id !== undefined" />
        </el-form-item>
        <el-form-item label="配置类型" prop="configType">
          <el-select v-model="form.configType" placeholder="请选择配置类型" class="w-full">
            <el-option label="文本框" value="text" />
            <el-option label="文本域" value="textarea" />
            <el-option label="下拉框" value="select" />
            <el-option label="单选框" value="radio" />
            <el-option label="复选框" value="checkbox" />
            <el-option label="图片上传" value="image" />
            <el-option label="文件上传" value="file" />
            <el-option label="开关" value="switch" />
          </el-select>
        </el-form-item>
        <el-form-item label="配置值" prop="configValue">
          <template v-if="form.configType === 'textarea'">
            <el-input 
              v-model="form.configValue" 
              type="textarea" 
              :rows="4"
              :placeholder="getConfigPlaceholder(form.configType)"
            />
          </template>
          <template v-else-if="form.configType === 'select'">
            <el-select 
              v-model="form.configValue"
              class="w-full"
              :placeholder="getConfigPlaceholder(form.configType)"
            >
              <el-option 
                v-for="option in parseConfigOptions(form.configOptions)"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </template>
          <template v-else-if="form.configType === 'radio'">
            <el-radio-group v-model="form.configValue">
              <el-radio 
                v-for="option in parseConfigOptions(form.configOptions)"
                :key="option.value"
                :label="option.value"
              >{{ option.label }}</el-radio>
            </el-radio-group>
          </template>
          <template v-else-if="form.configType === 'checkbox'">
            <el-checkbox-group v-model="form.configValue">
              <el-checkbox 
                v-for="option in parseConfigOptions(form.configOptions)"
                :key="option.value"
                :label="option.value"
              >{{ option.label }}</el-checkbox>
            </el-checkbox-group>
          </template>
          <template v-else-if="form.configType === 'switch'">
            <el-switch v-model="form.configValue" />
          </template>
          <template v-else-if="['image', 'file'].includes(form.configType)">
            <image-upload
              v-if="form.configType === 'image'"
              v-model="form.configValue"
              :limit="1"
              :fileSize="5"
              :fileType="['png', 'jpg', 'jpeg', 'gif']"
              :isShowTip="true"
              :multiple="false"
            />
            <file-upload
              v-else
              v-model="form.configValue"
              :limit="1"
              :fileSize="10"
              :isShowTip="true"
              :multiple="false"
            />

          </template>
          <template v-else>
            <el-input 
              v-model="form.configValue" 
              :placeholder="getConfigPlaceholder(form.configType)"
            />
          </template>
        </el-form-item>
        <el-form-item label="配置选项" prop="configOptions" v-if="['select', 'radio', 'checkbox'].includes(form.configType)">
          <el-input v-model="form.configOptions" type="textarea" placeholder="请输入选项，格式：value=label，每行一个" />
        </el-form-item>
        <el-form-item label="配置分组" prop="configGroup">
          <el-select v-model="form.configGroup" placeholder="请选择配置分组" class="w-full">
            <el-option label="基础配置" value="base" />
            <el-option label="系统配置" value="system" />
            <el-option label="上传配置" value="upload" />
            <el-option label="其他配置" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" class="w-full" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Config" lang="ts">
import { listConfig, getConfig, delConfig, addConfig, updateConfig } from '@/api/cms/config';
import { ConfigVO, ConfigQuery, ConfigForm } from '@/api/cms/config/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const configList = ref<ConfigVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const configFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ConfigForm = {
  id: undefined,
  configKey: undefined,
  configValue: undefined,
  configName: undefined,
  configType: undefined,
  configOptions: undefined,
  configGroup: undefined,
  isSystem: undefined,
  sort: undefined,
  remark: undefined,
}
const data = reactive<PageData<ConfigForm, ConfigQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    configKey: undefined,
    configValue: undefined,
    configName: undefined,
    configType: undefined,
    configOptions: undefined,
    configGroup: undefined,
    isSystem: undefined,
    sort: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "配置ID不能为空", trigger: "blur" }
    ],
    configKey: [
      { required: true, message: "配置键不能为空", trigger: "blur" }
    ],
    configValue: [
      { required: true, message: "配置值不能为空", trigger: "blur" }
    ],
    configName: [
      { required: true, message: "配置名称不能为空", trigger: "blur" }
    ],
    configType: [
      { required: true, message: "配置类型(text=文本框,textarea=文本域,select=下拉框,radio=单选框,checkbox=复选框,image=图片上传,file=文件上传,switch=开关)不能为空", trigger: "change" }
    ],
    configOptions: [
      { required: true, message: "配置选项(当config_type为select,radio,checkbox时使用)不能为空", trigger: "blur" }
    ],
    configGroup: [
      { required: true, message: "配置分组(base=基础配置,system=系统配置,upload=上传配置,other=其他配置)不能为空", trigger: "blur" }
    ],
    isSystem: [
      { required: true, message: "是否系统内置(0=否,1=是)不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "排序不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询CMS系统配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listConfig(queryParams.value);
  configList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  configFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ConfigVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加CMS系统配置";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ConfigVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getConfig(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改CMS系统配置";
}

/** 提交按钮 */
const submitForm = () => {
  configFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateConfig(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addConfig(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ConfigVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除CMS系统配置编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delConfig(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('cms/config/export', {
    ...queryParams.value
  }, `config_${new Date().getTime()}.xlsx`)
}

// 添加配置类型和分组的工具方法
const getConfigTypeLabel = (type: string) => {
  const types = {
    text: '文本框',
    textarea: '文本域',
    select: '下拉框',
    radio: '单选框',
    checkbox: '复选框',
    image: '图片上传',
    file: '文件上传',
    switch: '开关'
  };
  return types[type] || type;
};

const getConfigTypeTag = (type: string) => {
  const tags = {
    text: '',
    textarea: 'info',
    select: 'success',
    radio: 'warning',
    checkbox: 'warning',
    image: 'danger',
    file: 'danger',
    switch: 'success'
  };
  return tags[type] || '';
};

const getConfigGroupLabel = (group: string) => {
  const groups = {
    base: '基础配置',
    system: '系统配置',
    upload: '上传配置',
    other: '其他配置'
  };
  return groups[group] || group;
};

const getConfigGroupTag = (group: string) => {
  const tags = {
    base: 'success',
    system: 'info',
    upload: 'warning',
    other: ''
  };
  return tags[group] || '';
};

// 根据配置类型获取对应的表单组件
const getConfigComponent = (type: string) => {
  const components = {
    text: 'el-input',
    textarea: 'el-input',
    select: 'el-select',
    radio: 'el-radio-group',
    checkbox: 'el-checkbox-group',
    image: 'el-upload',
    file: 'el-upload',
    switch: 'el-switch'
  };
  return components[type] || 'el-input';
};

// 解析配置选项
const parseConfigOptions = (options: string) => {
  if (!options) return [];
  return options.split('\n').map(item => {
    const [value, label] = item.split('=');
    return { value, label: label || value };
  });
};

// 根据配置类型获取占位符文本
const getConfigPlaceholder = (type: string) => {
  const placeholders = {
    text: '请输入文本',
    textarea: '请输入长文本',
    select: '请选择选项',
    radio: '请选择选项',
    checkbox: '请选择选项',
    image: '请上传图片',
    file: '请上传文件',
    switch: ''
  };
  return placeholders[type] || '请输入内容';
};

/** 上传成功回调 */
const handleUploadSuccess = (response: any) => {
  form.value.configValue = response.url;
  proxy?.$modal.msgSuccess("上传成功");
}

/** 上传前校验 */
const handleBeforeUpload = (file: File) => {
  if (form.configType === 'image') {
    const isImage = file.type.startsWith('image/');
    const isLt500K = file.size / 1024 < 500;

    if (!isImage) {
      proxy?.$modal.msgError('上传文件只能是图片格式!');
      return false;
    }
    if (!isLt500K) {
      proxy?.$modal.msgError('上传图片大小不能超过 500KB!');
      return false;
    }
  } else {
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      proxy?.$modal.msgError('上传文件大小不能超过 2MB!');
      return false;
    }
  }
  return true;
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.config-form-item {
  margin-bottom: 20px;
}
</style>
